from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from backend.third_party.jwt_tool import toolJWT
from backend.utils.redis_client import redis_client


class JWTAuthMiddleware(MiddlewareMixin):
    """
    JWT认证中间件
    """
    
    def __init__(self, get_response=None):
        super().__init__(get_response)
        # 白名单路径，不需要验证token
        self.white_list = [
            '/accounts/login/',
            '/accounts/register/',
            '/accounts/send-sms/',
            '/accounts/sms-login/',
            '/accounts/getimagecode/',
            '/accounts/refresh-token/',
            '/admin/',
            '/api-auth/',
        ]
    
    def process_request(self, request):
        """
        处理请求，验证token
        """
        # 获取当前访问的路径
        current_path = request.path
        
        # 检查是否在白名单中
        if any(current_path.startswith(path) for path in self.white_list):
            return None
        
        # 从请求头获取token
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return JsonResponse({
                'code': 401,
                'msg': '缺少认证token'
            }, status=401)
        
        # 验证token格式
        if not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': 401,
                'msg': 'token格式错误'
            }, status=401)
        
        token = auth_header.split(' ')[1]
        
        # 验证token
        verify_result = toolJWT.verify_token(token)
        if not verify_result['valid']:
            return JsonResponse({
                'code': 401,
                'msg': verify_result['error']
            }, status=401)
        
        payload = verify_result['payload']
        
        # 检查token类型
        if payload.get('type') != 'access':
            return JsonResponse({
                'code': 401,
                'msg': 'token类型错误'
            }, status=401)
        
        # 检查用户是否退出（可选，如果实现了退出功能）
        user_id = payload.get('id')
        if user_id and redis_client.exists(f'logout:{user_id}'):
            return JsonResponse({
                'code': 401,
                'msg': '用户已退出登录'
            }, status=401)
        
        # 将用户信息添加到request中，供视图使用
        request.user_info = payload
        
        return None 